/*  Jarpa 1.05 - Java Packaging for Flash Lite Developers
 * 
 *  Recently, a new generation of mobile phones with support for Java ME and Flash Lite 
 *  has been taking widespread acceptance by the market, opening the door
 *  for hybrid applications. Looking for this business potential Jarpa was created
 *  allowing Flash Lite Developers deliver their content as Java ME applications.
 * 
 *  @author Felipe Andrade <felipe.andrade@i2tecnologia.com.br>
 * 
 *  http://www.i2tecnologia.com.br/jarpa/
 *  http://blog.felipeandrade.org/
 *  http://www.biskero.org
 */

package com.i2tecnologia.jarpa;

import java.io.DataOutputStream;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

public class Resources {
    public static Resources _instance;
        
    // data from the swf
    private InputStream _incomingData;
    
    private String _contentFolder = "";
    private String _toFolder = "";
    private String _fromFolder = "";

    public static Resources getInstance() {
        if(_instance == null)
            _instance = new Resources();
        
        return _instance;
    }
    
    public void copyResources(String aFolder) {
        _toFolder = aFolder;
        int index = aFolder.lastIndexOf('/');
        String fileName = aFolder.substring(index + 1, aFolder.length());
        
        _contentFolder = aFolder.substring(0, index);        
        _fromFolder = "/res/" + (fileName);
        
        try {
            // get resources from the jar
            this._incomingData = this.getClass().getResourceAsStream(this._fromFolder);

            // open a connection (sign problems ... on N95 only working in the memory card)
            FileConnection fConn = (FileConnection)Connector.open(this._toFolder);                        
            FileConnection fContent = (FileConnection)Connector.open(this._contentFolder);

            if(!fContent.exists()){
                fContent.mkdir();
            }
            
            fContent.close();

            // if not exists creates the file
            if (!fConn.exists()) {
                fConn.create();

                int ch = 0;
                DataOutputStream dataStorage = fConn.openDataOutputStream();

                // write to the file
                while ((ch = this._incomingData.read()) > -1) {
                    dataStorage.write(ch);
               }

               // closes
               dataStorage.flush();
               dataStorage.close();

               if(this._incomingData != null)
                   this._incomingData.close();
            }

            fConn.close();           
        } catch (Exception e) {
            
        }
    }
}
